<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学院管理 - 推免系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
        }

        .header {
            background: #fff;
            padding: 15px 20px;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            color: #333;
            font-size: 20px;
        }

        .user-info {
            color: #666;
        }

        .container {
            display: flex;
            min-height: calc(100vh - 60px);
        }

        .sidebar {
            width: 200px;
            background: #fff;
            border-right: 1px solid #e8e8e8;
            padding: 20px 0;
        }

        .menu-item {
            padding: 12px 20px;
            cursor: pointer;
            border-left: 3px solid transparent;
            color: #666;
        }

        .menu-item.active {
            background: #f0f7ff;
            border-left-color: #1890ff;
            color: #1890ff;
        }

        .menu-item:hover {
            background: #f5f5f5;
        }

        .main-content {
            flex: 1;
            padding: 20px;
            background: #fff;
            margin: 20px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e8e8e8;
        }

        .page-title {
            font-size: 18px;
            color: #333;
        }

        .breadcrumb {
            color: #666;
            font-size: 14px;
        }

        .breadcrumb a {
            color: #1890ff;
            text-decoration: none;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        .actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #1890ff;
            color: white;
            border-color: #1890ff;
        }

        .btn-danger {
            background: #ff4d4f;
            color: white;
            border-color: #ff4d4f;
        }

        .btn:hover {
            opacity: 0.8;
        }

        .search-box {
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            width: 200px;
        }

        .stats {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            border-left: 4px solid #52c41a;
        }

        .stats span {
            margin-right: 20px;
            color: #666;
        }

        .stats strong {
            color: #52c41a;
            font-size: 18px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e8e8e8;
        }

        th {
            background: #fafafa;
            font-weight: 600;
            color: #333;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-btn {
            padding: 4px 8px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }

        .edit-btn {
            background: #1890ff;
            color: white;
        }

        .delete-btn {
            background: #ff4d4f;
            color: white;
        }

        .admin-btn {
            background: #52c41a;
            color: white;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 6px;
            min-width: 400px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e8e8e8;
        }

        .close {
            font-size: 20px;
            cursor: pointer;
            color: #999;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 500;
        }

        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
        }

        .form-control:focus {
            border-color: #1890ff;
            outline: none;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #e8e8e8;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .empty-state img {
            width: 64px;
            height: 64px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .tab-container {
            margin-bottom: 20px;
        }

        .tab-buttons {
            display: flex;
            border-bottom: 1px solid #e8e8e8;
        }

        .tab-button {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
        }

        .tab-button.active {
            border-bottom-color: #1890ff;
            color: #1890ff;
        }

        .tab-content {
            display: none;
            padding: 15px 0;
        }

        .tab-content.active {
            display: block;
        }

        .tree-node {
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
            transition: background-color 0.2s;
        }

        .tree-node:hover {
            background-color: #f8f9fa;
        }

        .tree-node-content {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 15px;
        }

        .tree-node-info {
            flex: 1;
            min-width: 0;
        }

        .node-name {
            font-weight: 500;
            color: #333;
            margin: 0 8px;
        }

        .node-score {
            color: #52c41a;
            font-size: 14px;
        }

        .node-description {
            color: #666;
            font-size: 13px;
            line-height: 1.4;
            margin-top: 4px;
            background: #f8f9fa;
            padding: 8px 12px;
            border-radius: 4px;
            border-left: 3px solid #e8e8e8;
        }

        .debug-info {
            background: #f8f9fa;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-size: 12px;
            color: #666;
            display: none;
        }

        .category-selector {
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 6px;
            border-left: 4px solid #1890ff;
        }

        .category-selector label {
            font-weight: 600;
            margin-right: 10px;
            color: #333;
        }

        .category-selector select {
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            min-width: 200px;
            margin-right: 10px;
        }

        .current-category-info {
            display: inline-block;
            margin-left: 15px;
            padding: 5px 10px;
            background: #e6f7ff;
            border-radius: 4px;
            color: #1890ff;
            font-size: 14px;
        }

        .no-category-selected {
            text-align: center;
            padding: 40px;
            color: #999;
            background: #fafafa;
            border-radius: 6px;
            margin: 20px 0;
        }

        /* 新增：指标点分类统计样式 */
        .category-stats {
            background: #f0f7ff;
            padding: 12px 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            border-left: 4px solid #1890ff;
        }

        .category-stats span {
            margin-right: 20px;
            color: #666;
        }

        .category-stats strong {
            color: #1890ff;
        }

        .level-badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
            color: white;
            margin-right: 8px;
        }
        .level-1 { background: #1890ff; }
        .level-2 { background: #52c41a; }
        .level-3 { background: #faad14; }
        .level-4 { background: #f5222d; }
        .level-5 { background: #722ed1; }
        .level-6 { background: #13c2c2; }
        .level-7 { background: #eb2f96; }
        .level-8 { background: #fa541c; }
        .level-9 { background: #a0d911; }
        .level-10 { background: #2f54eb; }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .tree-node-content {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }

            .action-buttons {
                align-self: flex-end;
            }
        }
    </style>
</head>
<body>
<!-- 头部导航 -->
<div class="header">
    <h1>推免系统 - 学院管理员</h1>
    <div class="user-info">
        <span id="userRoleDisplay">学院管理员</span>
        <button class="btn" onclick="logout()" style="margin-left: 10px;">退出登录</button>
    </div>
</div>

<!-- 主体容器 -->
<div class="container">
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="menu-item active" onclick="switchTab('indicator-points')">指标点管理</div>
        <div class="menu-item" onclick="switchTab('categories')">专业类别管理</div>
        <div class="menu-item" onclick="switchTab('counselors')">辅导员管理</div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb" id="breadcrumb">
            <a href="collegeadmin-dashboard.html">学院管理</a> &gt;
            <span id="currentCollegeName">加载中...</span>
        </div>

        <!-- 标签页容器 -->
        <div class="tab-container">
            <div class="tab-buttons">
                <div class="tab-button active" data-tab="indicator-points">指标点管理</div>
                <div class="tab-button" data-tab="categories">专业类别管理</div>
                <div class="tab-button" data-tab="counselors">辅导员管理</div>
            </div>

            <!-- 指标点管理标签页 -->
            <div class="tab-content active" id="indicator-points-tab">
                <div class="page-header">
                    <h2 class="page-title">指标点管理</h2>
                    <div class="actions">
                        <input type="text" class="search-box" id="indicatorSearchInput" placeholder="搜索指标点...">
                        <button class="btn" onclick="searchIndicatorPoints()">搜索</button>
                        <button class="btn btn-primary" onclick="showAddIndicatorPointModal()" id="addIndicatorBtn" disabled>添加指标点</button>
                        <button class="btn" onclick="loadIndicatorPoints()">刷新</button>
                    </div>
                </div>

                <!-- 专业类别选择器 -->
                <div class="category-selector">
                    <label for="majorCategorySelect">选择专业类别：</label>
                    <select id="majorCategorySelect" onchange="onCategoryChange()">
                        <option value="">请选择专业类别...</option>
                        <!-- 动态填充 -->
                    </select>
                    <span class="current-category-info" id="currentCategoryInfo" style="display: none;">
                        当前类别：<strong id="currentCategoryName">未选择</strong>
                    </span>
                </div>

                <!--统计-->
                <div class="category-stats" id="indicatorStats" style="display: none;">
                    当前类别指标点总数：<strong id="indicatorCount">0</strong>
                </div>

                <!-- 指标点树形容器 -->
                <div id="indicatorTreeContainer">
                    <div class="no-category-selected" id="noCategorySelected">
                        <h3>请先选择专业类别</h3>
                        <p>在上方选择专业类别后，即可查看和管理该类别下的指标点</p>
                    </div>
                </div>
            </div>

            <!-- 专业类别管理标签页 -->
            <div class="tab-content" id="categories-tab">
                <div class="page-header">
                    <h2 class="page-title">专业类别管理</h2>
                    <div class="actions">
                        <input type="text" class="search-box" id="categorySearchInput" placeholder="搜索类别...">
                        <button class="btn" onclick="searchCategories()">搜索</button>
                        <button class="btn btn-primary" onclick="showAddCategoryModal()">添加类别</button>
                        <button class="btn" onclick="loadCategories()">刷新</button>
                    </div>
                </div>

                <div class="stats" id="categoryStats">
                    当前类别总数：<strong id="categoryCount">0</strong>
                </div>

                <table id="categoryTable">
                    <thead>
                    <tr>
                        <th>类别名称</th>
                        <th>计算规则</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="categoryTableBody">
                    <!-- 动态填充 -->
                    </tbody>
                </table>
            </div>

            <!-- 辅导员管理标签页 -->
            <div class="tab-content" id="counselors-tab">
                <div class="page-header">
                    <h2 class="page-title">辅导员管理</h2>
                    <div class="actions">
                        <input type="text" class="search-box" id="counselorSearchInput" placeholder="搜索辅导员...">
                        <button class="btn" onclick="searchCounselors()">搜索</button>
                        <button class="btn btn-primary" onclick="showAddCounselorModal()">添加辅导员</button>
                        <button class="btn" onclick="loadCounselors()">刷新</button>
                    </div>
                </div>

                <div class="stats" id="counselorStats">
                    当前辅导员总数：<strong id="counselorCount">0</strong>
                </div>

                <table id="counselorTable">
                    <thead>
                    <tr>
                        <th>姓名</th>
                        <th>账号</th>
                        <th>手机号</th>
                        <th>所属类别</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="counselorTableBody">
                    <!-- 动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 所有模态框 -->
<div id="addIndicatorPointModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>添加指标点</h3>
            <span class="close" onclick="closeAddIndicatorPointModal()">&times;</span>
        </div>
        <form id="addIndicatorPointForm">
            <div class="form-group">
                <label for="indicatorPointName">名称 *</label>
                <input type="text" id="indicatorPointName" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="indicatorPointDescription">描述</label>
                <textarea id="indicatorPointDescription" class="form-control"></textarea>
            </div>
            <div class="form-group">
                <label for="indicatorPointMaxScore">最大分值</label>
                <input type="number" step="0.01" id="indicatorPointMaxScore" class="form-control">
            </div>
            <div class="form-group">
                <label for="indicatorPointParent">父级指标点</label>
                <select id="indicatorPointParent" class="form-control" onchange="onParentChange()">
                    <option value="">无 (一级指标)</option>
                    <!-- 动态填充 -->
                </select>
            </div>
            <div class="form-group">
                <label for="indicatorPointIsLeaf">节点类型</label>
                <select id="indicatorPointIsLeaf" class="form-control">
                    <option value="true">叶子节点</option>
                    <option value="false">非叶子节点</option>
                </select>
                <small style="color: #666;">
                    叶子节点<br>
                    非叶子节点
                </small>
            </div>
        </form>
        <div class="modal-footer">
            <button class="btn" onclick="closeAddIndicatorPointModal()">取消</button>
            <button class="btn btn-primary" onclick="addIndicatorPoint()">确定</button>
        </div>
    </div>
</div>

<div id="editIndicatorPointModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>编辑指标点</h3>
            <span class="close" onclick="closeEditIndicatorPointModal()">&times;</span>
        </div>
        <form id="editIndicatorPointForm">
            <input type="hidden" id="editIndicatorPointId">
            <div class="form-group">
                <label for="editIndicatorPointName">名称 *</label>
                <input type="text" id="editIndicatorPointName" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="editIndicatorPointDescription">描述</label>
                <textarea id="editIndicatorPointDescription" class="form-control"></textarea>
            </div>
            <div class="form-group">
                <label for="editIndicatorPointMaxScore">最大分值</label>
                <input type="number" step="0.01" id="editIndicatorPointMaxScore" class="form-control">
            </div>
            <div class="form-group">
                <label for="editIndicatorPointIsLeaf">节点类型</label>
                <select id="editIndicatorPointIsLeaf" class="form-control">
                    <option value="true">叶子节点</option>
                    <option value="false">非叶子节点</option>
                </select>
                <small style="color: #666;" id="editLeafNodeTip">
                    叶子节点：不可添加子项<br>
                    非叶子节点：可以继续添加子项
                </small>
            </div>
        </form>
        <div class="modal-footer">
            <button class="btn" onclick="closeEditIndicatorPointModal()">取消</button>
            <button class="btn btn-primary" onclick="updateIndicatorPoint()">确定</button>
        </div>
    </div>
</div>

<div id="addCategoryModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>添加专业类别</h3>
            <span class="close" onclick="closeAddCategoryModal()">&times;</span>
        </div>
        <form id="addCategoryForm">
            <div class="form-group">
                <label for="categoryName">类别名称 *</label>
                <input type="text" id="categoryName" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="categoryCalculationRule">计算规则</label>
                <textarea id="categoryCalculationRule" class="form-control" placeholder="JSON格式的计算规则"></textarea>
            </div>
        </form>
        <div class="modal-footer">
            <button class="btn" onclick="closeAddCategoryModal()">取消</button>
            <button class="btn btn-primary" onclick="addCategory()">确定</button>
        </div>
    </div>
</div>

<div id="editCategoryModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>编辑专业类别</h3>
            <span class="close" onclick="closeEditCategoryModal()">&times;</span>
        </div>
        <form id="editCategoryForm">
            <input type="hidden" id="editCategoryId">
            <div class="form-group">
                <label for="editCategoryName">类别名称 *</label>
                <input type="text" id="editCategoryName" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="editCategoryCalculationRule">计算规则</label>
                <textarea id="editCategoryCalculationRule" class="form-control"></textarea>
            </div>
        </form>
        <div class="modal-footer">
            <button class="btn" onclick="closeEditCategoryModal()">取消</button>
            <button class="btn btn-primary" onclick="updateCategory()">确定</button>
        </div>
    </div>
</div>

<div id="addCounselorModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>添加辅导员</h3>
            <span class="close" onclick="closeAddCounselorModal()">&times;</span>
        </div>
        <form id="addCounselorForm">
            <div class="form-group">
                <label for="counselorName">姓名 *</label>
                <input type="text" id="counselorName" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="counselorAccount">账号 *</label>
                <input type="text" id="counselorAccount" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="counselorTel">手机号</label>
                <input type="tel" id="counselorTel" class="form-control">
            </div>
            <div class="form-group">
                <label for="counselorCategory">所属类别</label>
                <select id="counselorCategory" class="form-control">
                    <!-- 动态填充 -->
                </select>
            </div>
            <div class="form-group">
                <label for="counselorPassword">初始密码</label>
                <input type="text" id="counselorPassword" class="form-control" placeholder="留空则使用账号作为密码">
            </div>
        </form>
        <div class="modal-footer">
            <button class="btn" onclick="closeAddCounselorModal()">取消</button>
            <button class="btn btn-primary" onclick="addCounselor()">确定</button>
        </div>
    </div>
</div>

<!-- 调试信息 -->
<div id="debugInfo" class="debug-info">
    <strong>调试信息:</strong>
    <div id="debugContent"></div>
</div>

<script>
    // 全局变量
    let currentCollegeId = null;
    let currentCollegeName = '';
    let indicatorPoints = [];
    let categories = [];
    let counselors = [];
    let debugMode = false;
    let selectedCategoryId = '';
    let selectedCategoryName = '';

    // 页面加载
    document.addEventListener('DOMContentLoaded', function () {
        if (!checkLogin()) return;
        loadCategories().then(() => {
            loadCounselors();
        });

        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 'd') {
                e.preventDefault();
                debugCategories();
                alert('类别调试信息已输出到控制台');
            }
        });

        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.addEventListener('click', function() {
                const tabName = this.dataset.tab;
                switchTab(tabName);
                if (tabName === 'counselors') {
                    loadCounselors();
                }
            });
        });
    });

    // 检查登录状态
    function checkLogin() {
        const token = localStorage.getItem('token');
        const role = localStorage.getItem('role');
        let user = {};

        try {
            user = JSON.parse(localStorage.getItem('user') || '{}');
        } catch (e) {
            console.error('解析用户信息失败:', e);
            alert('用户信息异常，请重新登录');
            window.location.href = 'login.html';
            return false;
        }

        if (!token || role !== 'yHJ7' || !user.collegeId) {
            alert('请先登录学院管理员账号');
            window.location.href = 'login.html';
            return false;
        }

        currentCollegeId = String(user.collegeId);
        currentCollegeName = user.collegeName || '当前学院';

        document.getElementById('currentCollegeName').textContent = currentCollegeName;
        document.getElementById('breadcrumb').innerHTML = `
            <a href="collegeadmin-dashboard.html">学院管理</a> &gt;
            ${currentCollegeName}
        `;

        return true;
    }

    // 切换标签页
    function switchTab(tabName) {
        document.querySelectorAll('.menu-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`.menu-item[onclick="switchTab('${tabName}')"]`).classList.add('active');

        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`.tab-button[data-tab="${tabName}"]`).classList.add('active');

        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-tab`).classList.add('active');
    }

    // 获取认证头
    function getAuthHeaders() {
        const token = localStorage.getItem('token');
        if (!token) {
            alert('登录已过期，请重新登录');
            window.location.href = 'login.html';
            return {};
        }
        return {
            'Content-Type': 'application/json',
            'token': token
        };
    }

    // 显示调试信息
    function showDebugInfo(message) {
        if (debugMode) {
            const debugContent = document.getElementById('debugContent');
            const timestamp = new Date().toLocaleTimeString();
            debugContent.innerHTML += `[${timestamp}] ${message}<br>`;
            console.log(message);
        }
    }

    // 切换调试模式
    function toggleDebug() {
        debugMode = !debugMode;
        document.getElementById('debugInfo').style.display = debugMode ? 'block' : 'none';
        showDebugInfo(`调试模式 ${debugMode ? '开启' : '关闭'}`);
    }

    // 退出登录
    function logout() {
        if (confirm('确定要退出登录吗？')) {
            localStorage.removeItem('token');
            localStorage.removeItem('role');
            localStorage.removeItem('user');
            window.location.href = 'login.html';
        }
    }

    // ==================== 指标点管理 ====================
    async function loadIndicatorPoints() {
        if (!selectedCategoryId) {
            alert('请先选择专业类别');
            return;
        }
        await loadIndicatorPointsByCategory(selectedCategoryId);
    }

    async function loadIndicatorPointsByCategory(categoryId) {
        try {
            showDebugInfo(`开始加载类别 ${categoryId} 的指标点数据...`);
            const response = await fetch(`/api/collegeadmin/indicatorpoints/tree?majorCategoryId=${categoryId}`, {
                method: 'GET',
                headers: getAuthHeaders()
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            showDebugInfo(`指标点加载结果: code=${result.code}, count=${result.data ? result.data.length : 0}`);

            if (result.code === 200) {
                indicatorPoints = result.data || [];
                renderIndicatorTree(indicatorPoints);
                updateIndicatorStats(indicatorPoints);
            } else {
                alert('加载指标点失败: ' + result.message);
                resetIndicatorView();
            }
        } catch (error) {
            console.error('加载指标点失败:', error);
            showDebugInfo('加载指标点失败: ' + error.message);
            alert('加载指标点失败');
            resetIndicatorView();
        }
    }

    function updateIndicatorStats(treeData) {
        let totalCount = 0;

        const countNodes = (nodes) => {
            nodes.forEach(node => {
                totalCount++;
                if (node.children && node.children.length > 0) {
                    countNodes(node.children);
                }
            });
        };

        countNodes(treeData);

        document.getElementById('indicatorCount').textContent = totalCount;
    }

    function renderIndicatorTree(treeData) {
        const container = document.getElementById('indicatorTreeContainer');
        container.innerHTML = '';

        if (!treeData || treeData.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <h3>暂无指标点</h3>
                    <p>当前类别下还没有指标点，点击"添加指标点"按钮开始创建</p>
                </div>
            `;
            return;
        }

        const buildTreeHTML = (nodes, level = 0) => {
            let html = '';
            nodes.forEach(node => {
                const indentPx = level * 24;
                const levelClass = `level-${level + 1}`;

                html += `
                    <div class="tree-node" style="margin-left: ${indentPx}px;">
                        <div class="tree-node-content">
                            <div class="tree-node-info">
                                <span class="level-badge ${levelClass}">${level + 1}级</span>
                                <span class="node-name">${node.name}</span>
                                ${node.maxScore ? `<span class="node-score">(${node.maxScore}分)</span>` : ''}
                                ${node.description ? `<div class="node-description">${node.description}</div>` : ''}
                            </div>
                            <div class="action-buttons">
                                <button class="action-btn edit-btn" onclick="editIndicatorPointById('${node.id}')">编辑</button>
                                <button class="action-btn delete-btn" onclick="deleteIndicatorPoint('${node.id}', '${escapeHtml(node.name)}')">删除</button>
                                ${!node.isLeaf ? `<button class="action-btn" onclick="showAddIndicatorPointModal('${node.id}')">添加子项</button>` : ''}
                            </div>
                        </div>
                    </div>
                `;

                if (node.children && node.children.length > 0) {
                    html += buildTreeHTML(node.children, level + 1);
                }
            });
            return html;
        };

        container.innerHTML = buildTreeHTML(treeData);
    }
    function editIndicatorPointById(id) {
        const node = findIndicatorPointById(id);
        if (node) {
            editIndicatorPoint(
                node.id,
                node.name,
                node.description || '',
                node.maxScore || 0,
                node.isLeaf
            );
        } else {
            alert('找不到指标点数据');
        }
    }

    function onCategoryChange() {
        const categorySelect = document.getElementById('majorCategorySelect');
        selectedCategoryId = categorySelect.value;

        //安全检查
        const currentCategoryInfo = document.getElementById('currentCategoryInfo');
        const indicatorStats = document.getElementById('indicatorStats');
        const noCategorySelected = document.getElementById('noCategorySelected');
        const addIndicatorBtn = document.getElementById('addIndicatorBtn');

        if (!currentCategoryInfo || !indicatorStats || !noCategorySelected || !addIndicatorBtn) {
            console.error('必要的页面元素未找到');
            return;
        }

        if (selectedCategoryId) {
            const selectedCategory = categories.find(cat => cat.id === selectedCategoryId);
            selectedCategoryName = selectedCategory ? selectedCategory.name : '未知类别';

            document.getElementById('currentCategoryName').textContent = selectedCategoryName;
            currentCategoryInfo.style.display = 'inline-block';
            indicatorStats.style.display = 'block';
            noCategorySelected.style.display = 'none';
            addIndicatorBtn.disabled = false;

            loadIndicatorPointsByCategory(selectedCategoryId);
        } else {
            resetIndicatorView();
        }
    }

    function resetIndicatorView() {
        document.getElementById('currentCategoryInfo').style.display = 'none';
        document.getElementById('indicatorStats').style.display = 'none';
        document.getElementById('addIndicatorBtn').disabled = true;
        document.getElementById('indicatorTreeContainer').innerHTML = `
            <div class="no-category-selected" id="noCategorySelected">
                <div style="font-size: 48px; margin-bottom: 16px;">📊</div>
                <h3>请先选择专业类别</h3>
                <p>在上方选择专业类别后，即可查看和管理该类别下的指标点</p>
            </div>
        `;
    }

    // 父级选择变化时的处理
    function onParentChange() {
        const parentSelect = document.getElementById('indicatorPointParent');
        const isLeafSelect = document.getElementById('indicatorPointIsLeaf');

        if (parentSelect.value === '') {
            // 选择一级指标时，默认设为非叶子节点
            isLeafSelect.value = 'false';
            isLeafSelect.disabled = false;
        } else {
            // 选择子级指标时，允许选择叶子节点
            isLeafSelect.disabled = false;
        }
    }

    function showAddIndicatorPointModal(parentId = '') {
        if (!selectedCategoryId) {
            alert('请先选择专业类别');
            return;
        }

        const modal = document.getElementById('addIndicatorPointModal');
        const parentSelect = document.getElementById('indicatorPointParent');
        const isLeafSelect = document.getElementById('indicatorPointIsLeaf');

        // 重置表单
        document.getElementById('indicatorPointName').value = '';
        document.getElementById('indicatorPointDescription').value = '';
        document.getElementById('indicatorPointMaxScore').value = '';

        // 填充父级选择
        parentSelect.innerHTML = '<option value="">无 (一级指标)</option>';
        const addOptions = (nodes, level = 0, currentParentId = '') => {
            nodes.forEach(node => {
                // 只显示非叶子节点作为父级选项
                if (!node.isLeaf) {
                    const indent = '- '.repeat(level);
                    parentSelect.innerHTML += `<option value="${node.id}" ${parentId === node.id ? 'selected' : ''}>${indent}${node.name}</option>`;

                    if (node.children && node.children.length > 0) {
                        addOptions(node.children, level + 1, parentId);
                    }
                }
            });
        };

        addOptions(indicatorPoints);

        if (parentId) {
            parentSelect.value = parentId;
            // 如果有父节点，默认设为叶子节点
            isLeafSelect.value = 'true';
        } else {
            // 如果没有父节点（一级指标），默认设为非叶子节点
            isLeafSelect.value = 'false';
        }

        modal.style.display = 'block';
    }

    function closeAddIndicatorPointModal() {
        document.getElementById('addIndicatorPointModal').style.display = 'none';
    }

    async function addIndicatorPoint() {
        if (!selectedCategoryId) {
            alert('请先选择专业类别');
            return;
        }

        const name = document.getElementById('indicatorPointName').value.trim();
        const description = document.getElementById('indicatorPointDescription').value.trim();
        const maxScore = parseFloat(document.getElementById('indicatorPointMaxScore').value) || 0;
        const parentId = document.getElementById('indicatorPointParent').value;
        const isLeaf = document.getElementById('indicatorPointIsLeaf').value === 'true';

        if (!name) {
            alert('请输入指标点名称');
            return;
        }

        // 验证：如果选择了父节点，且父节点是叶子节点，则不能添加子节点
        if (parentId) {
            const parentNode = findIndicatorPointById(parentId);
            if (parentNode && parentNode.isLeaf) {
                alert('不能在叶子节点下添加子节点');
                return;
            }
        }

        try {
            const response = await fetch('/api/collegeadmin/indicatorpoints', {
                method: 'POST',
                headers: getAuthHeaders(),
                body: JSON.stringify({
                    name,
                    description,
                    maxScore,
                    parentId: parentId || null,
                    majorCategoryId: selectedCategoryId,
                    isLeaf: isLeaf
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                alert('添加成功');
                closeAddIndicatorPointModal();
                loadIndicatorPointsByCategory(selectedCategoryId);
            } else {
                alert('添加失败: ' + result.message);
            }
        } catch (error) {
            console.error('添加指标点失败:', error);
            alert('添加指标点失败');
        }
    }

    function editIndicatorPoint(id, name, description, maxScore, isLeaf) {
        const modal = document.getElementById('editIndicatorPointModal');
        document.getElementById('editIndicatorPointId').value = id;
        document.getElementById('editIndicatorPointName').value = name;
        document.getElementById('editIndicatorPointDescription').value = description || '';
        document.getElementById('editIndicatorPointMaxScore').value = maxScore || '';
        document.getElementById('editIndicatorPointIsLeaf').value = isLeaf ? 'true' : 'false';

        // 检查是否有子节点，如果有则不能改为叶子节点
        const node = findIndicatorPointById(id);
        const hasChildren = node && node.children && node.children.length > 0;

        if (hasChildren) {
            document.getElementById('editIndicatorPointIsLeaf').value = 'false';
            document.getElementById('editIndicatorPointIsLeaf').disabled = true;
            document.getElementById('editLeafNodeTip').innerHTML =
                '该节点存在子节点，不能改为叶子节点<br>' +
                '请先删除所有子节点后才能修改为叶子节点';
        } else {
            document.getElementById('editIndicatorPointIsLeaf').disabled = false;
            document.getElementById('editLeafNodeTip').innerHTML =
                '叶子节点：学生可以申报的具体项目<br>' +
                '非叶子节点：仅用于分类，不能直接申报';
        }

        modal.style.display = 'block';
    }

    function closeEditIndicatorPointModal() {
        document.getElementById('editIndicatorPointModal').style.display = 'none';
    }

    async function updateIndicatorPoint() {
        if (!selectedCategoryId) {
            alert('请先选择专业类别');
            return;
        }

        const id = document.getElementById('editIndicatorPointId').value;
        const name = document.getElementById('editIndicatorPointName').value.trim();
        const description = document.getElementById('editIndicatorPointDescription').value.trim();
        const maxScore = parseFloat(document.getElementById('editIndicatorPointMaxScore').value) || 0;
        const isLeaf = document.getElementById('editIndicatorPointIsLeaf').value === 'true';

        if (!name) {
            alert('请输入指标点名称');
            return;
        }

        try {
            const response = await fetch(`/api/collegeadmin/indicatorpoints/${id}`, {
                method: 'PUT',
                headers: getAuthHeaders(),
                body: JSON.stringify({
                    name,
                    description,
                    maxScore,
                    majorCategoryId: selectedCategoryId,
                    isLeaf: isLeaf
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                alert('更新成功');
                closeEditIndicatorPointModal();
                loadIndicatorPointsByCategory(selectedCategoryId);
            } else {
                alert('更新失败: ' + result.message);
            }
        } catch (error) {
            console.error('更新指标点失败:', error);
            alert('更新指标点失败');
        }
    }

    async function deleteIndicatorPoint(id, name) {
        if (!selectedCategoryId) {
            alert('请先选择专业类别');
            return;
        }

        if (!confirm(`确定要删除指标点 "${name}" 吗？此操作不可恢复！`)) {
            return;
        }

        try {
            const response = await fetch(`/api/collegeadmin/indicatorpoints/${id}`, {
                method: 'DELETE',
                headers: getAuthHeaders()
            });

            const result = await response.json();

            if (result.code === 200) {
                alert('删除成功');
                loadIndicatorPointsByCategory(selectedCategoryId);
            } else {
                alert('删除失败: ' + result.message);
            }
        } catch (error) {
            console.error('删除指标点失败:', error);
            alert('删除指标点失败');
        }
    }

    function searchIndicatorPoints() {
        const keyword = document.getElementById('indicatorSearchInput').value.toLowerCase();
        if (!keyword) {
            loadIndicatorPointsByCategory(selectedCategoryId);
            return;
        }

        const filteredPoints = filterIndicatorPoints(indicatorPoints, keyword);
        renderIndicatorTree(filteredPoints);
        updateIndicatorStats(filteredPoints);
    }

    function filterIndicatorPoints(nodes, keyword) {
        return nodes.reduce((result, node) => {
            const isMatch = node.name.toLowerCase().includes(keyword) ||
                (node.description && node.description.toLowerCase().includes(keyword));

            const matchedChildren = node.children ? filterIndicatorPoints(node.children, keyword) : [];

            if (isMatch || matchedChildren.length > 0) {
                result.push({
                    ...node,
                    children: matchedChildren
                });
            }
            return result;
        }, []);
    }

    // 辅助函数：根据ID查找指标点
    function findIndicatorPointById(id) {
        const findNode = (nodes, targetId) => {
            for (const node of nodes) {
                if (node.id === targetId) {
                    return node;
                }
                if (node.children && node.children.length > 0) {
                    const found = findNode(node.children, targetId);
                    if (found) return found;
                }
            }
            return null;
        };
        return findNode(indicatorPoints, id);
    }

    // ==================== 类别管理 ====================
    async function loadCategories() {
        try {
            console.log('开始加载类别数据...');
            const response = await fetch(`/api/collegeadmin/categories`, {
                method: 'GET',
                headers: getAuthHeaders()
            });

            const result = await response.json();
            console.log('类别加载原始结果:', result);

            if (result.code === 200) {
                categories = result.data;

                categories = categories.map(cat => {
                    const idStr = typeof cat.id === 'number' ? cat.id.toString() : String(cat.id);
                    return {
                        ...cat,
                        id: idStr
                    };
                });

                console.log('处理后的类别列表:', categories);
                renderCategories(categories);
                populateCategorySelector();
                document.getElementById('categoryCount').textContent = categories.length;
                return categories;
            } else {
                alert('加载类别失败: ' + result.message);
                return [];
            }
        } catch (error) {
            console.error('加载类别失败:', error);
            alert('加载类别失败');
            return [];
        }
    }

    function populateCategorySelector() {
        const categorySelect = document.getElementById('majorCategorySelect');
        categorySelect.innerHTML = '<option value="">请选择专业类别...</option>';

        if (categories.length === 0) {
            categorySelect.innerHTML += '<option value="" disabled>暂无专业类别</option>';
            return;
        }

        categories.forEach(category => {
            const option = document.createElement('option');
            option.value = category.id;
            option.textContent = category.name;
            categorySelect.appendChild(option);
        });
    }

    function renderCategories(categoryList) {
        const tbody = document.getElementById('categoryTableBody');
        tbody.innerHTML = '';

        if (categoryList.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4" class="empty-state">暂无类别，请点击"添加类别"按钮创建</td></tr>';
            return;
        }

        categoryList.forEach(category => {
            const row = document.createElement('tr');
            const categoryId = category.id.toString();

            row.innerHTML = `
                <td>${category.name}</td>
                <td>${category.calculationRule || '默认规则'}</td>
                <td>${formatDate(category.createTime)}</td>
                <td>
                    <div class="action-buttons">
                        <button class="action-btn edit-btn" onclick="editCategory('${categoryId}', '${escapeHtml(category.name)}', '${escapeHtml(category.calculationRule || '')}')">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteCategory('${categoryId}', '${escapeHtml(category.name)}')">删除</button>
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    function showAddCategoryModal() {
        document.getElementById('addCategoryModal').style.display = 'block';
    }

    function closeAddCategoryModal() {
        document.getElementById('addCategoryModal').style.display = 'none';
    }

    async function addCategory() {
        const name = document.getElementById('categoryName').value.trim();
        const calculationRule = document.getElementById('categoryCalculationRule').value.trim();

        if (!name) {
            alert('请输入类别名称');
            return;
        }

        try {
            const response = await fetch('/api/collegeadmin/categories', {
                method: 'POST',
                headers: getAuthHeaders(),
                body: JSON.stringify({
                    name,
                    calculationRule,
                    collegeId: currentCollegeId
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                alert('添加成功');
                closeAddCategoryModal();
                loadCategories();
            } else {
                alert('添加失败: ' + result.message);
            }
        } catch (error) {
            console.error('添加类别失败:', error);
            alert('添加类别失败');
        }
    }

    function editCategory(id, name, calculationRule) {
        const modal = document.getElementById('editCategoryModal');
        document.getElementById('editCategoryId').value = id;
        document.getElementById('editCategoryName').value = name;
        document.getElementById('editCategoryCalculationRule').value = calculationRule;
        modal.style.display = 'block';
    }

    function closeEditCategoryModal() {
        document.getElementById('editCategoryModal').style.display = 'none';
    }

    async function updateCategory() {
        const id = document.getElementById('editCategoryId').value;
        const name = document.getElementById('editCategoryName').value.trim();
        const calculationRule = document.getElementById('editCategoryCalculationRule').value.trim();

        if (!name) {
            alert('请输入类别名称');
            return;
        }

        try {
            const response = await fetch(`/api/collegeadmin/categories/${id}`, {
                method: 'PUT',
                headers: getAuthHeaders(),
                body: JSON.stringify({
                    name,
                    calculationRule
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                alert('更新成功');
                closeEditCategoryModal();
                loadCategories();
            } else {
                alert('更新失败: ' + result.message);
            }
        } catch (error) {
            console.error('更新类别失败:', error);
            alert('更新类别失败');
        }
    }

    async function deleteCategory(id, name) {
        if (!confirm(`确定要删除类别 "${name}" 吗？此操作会删除该类别下所有指标点，不可恢复！`)) {
            return;
        }

        try {
            const response = await fetch(`/api/collegeadmin/categories/${id}`, {
                method: 'DELETE',
                headers: getAuthHeaders()
            });

            const result = await response.json();

            if (result.code === 200) {
                alert('删除成功');
                loadCategories();
                resetIndicatorView();
            } else {
                alert('删除失败: ' + result.message);
            }
        } catch (error) {
            console.error('删除类别失败:', error);
            alert('删除类别失败');
        }
    }

    function searchCategories() {
        const keyword = document.getElementById('categorySearchInput').value.toLowerCase();
        const filteredCategories = categories.filter(cat =>
            cat.name.toLowerCase().includes(keyword)
        );
        renderCategories(filteredCategories);
    }

    // ==================== 辅导员管理 ====================
    async function loadCounselors() {
        try {
            console.log('加载辅导员数据，当前学院ID:', currentCollegeId);
            const response = await fetch(`/api/collegeadmin/counselors?collegeId=${currentCollegeId}`, {
                method: 'GET',
                headers: getAuthHeaders()
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('辅导员加载结果:', result);

            if (result.code === 200) {
                counselors = result.data || [];
                console.log('当前学院辅导员列表:', counselors);
                renderCounselors(counselors);
                document.getElementById('counselorCount').textContent = counselors.length;
            } else {
                alert('加载辅导员失败: ' + (result.message || '未知错误'));
                document.getElementById('counselorTableBody').innerHTML = '<tr><td colspan="5" class="empty-state">加载失败，请点击刷新重试</td></tr>';
                document.getElementById('counselorCount').textContent = '0';
            }
        } catch (error) {
            console.error('加载辅导员失败:', error);
            alert('加载辅导员失败: ' + error.message);
            document.getElementById('counselorTableBody').innerHTML = '<tr><td colspan="5" class="empty-state">网络异常，请检查后重试</td></tr>';
            document.getElementById('counselorCount').textContent = '0';
        }
    }

    function renderCounselors(counselorList) {
        const tbody = document.getElementById('counselorTableBody');
        tbody.innerHTML = '';

        if (!counselorList || counselorList.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" class="empty-state">暂无辅导员，请点击"添加辅导员"按钮创建</td></tr>';
            return;
        }

        counselorList.forEach(counselor => {
            const id = counselor.id ? String(counselor.id) : '';
            const name = counselor.name || '未知姓名';
            const account = counselor.account || '未知账号';
            const tel = counselor.tel || '-';
            const categoryName = counselor.majorCategoryName || '未分配类别';

            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${name}</td>
                <td>${account}</td>
                <td>${tel}</td>
                <td>${categoryName}</td>
                <td>
                    <div class="action-buttons">
                        ${id ? `<button class="action-btn delete-btn" onclick="deleteCounselor('${id}', '${escapeHtml(name)}')">删除</button>` : ''}
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    async function addCounselor() {
        const name = document.getElementById('counselorName').value.trim();
        const account = document.getElementById('counselorAccount').value.trim();
        const tel = document.getElementById('counselorTel').value.trim();
        const categorySelect = document.getElementById('counselorCategory');
        const categoryId = categorySelect.value;
        const password = document.getElementById('counselorPassword').value.trim();

        if (!name || !account) {
            alert('请输入姓名和账号');
            return;
        }
        if (!categoryId) {
            alert('请选择所属类别');
            return;
        }

        try {
            const requestData = {
                name,
                account,
                tel: tel || '',
                password: password || account,
                majorCategoryId: String(categoryId),
                collegeId: currentCollegeId
            };

            console.log('添加辅导员请求数据:', requestData);
            const response = await fetch('/api/collegeadmin/counselors', {
                method: 'POST',
                headers: getAuthHeaders(),
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            if (result.code === 200) {
                alert('添加成功');
                closeAddCounselorModal();
                loadCounselors();
            } else {
                alert('添加失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            console.error('添加辅导员失败:', error);
            alert('添加辅导员失败: ' + error.message);
        }
    }

    async function deleteCounselor(id, name) {
        if (!id) {
            alert('辅导员ID无效，无法删除');
            return;
        }
        if (!confirm(`确定要删除辅导员 "${name}" 吗？此操作不可恢复！`)) {
            return;
        }

        try {
            const counselorId = String(id);
            const response = await fetch(`/api/collegeadmin/counselors/${counselorId}`, {
                method: 'DELETE',
                headers: getAuthHeaders()
            });

            const result = await response.json();
            if (result.code === 200) {
                alert('删除成功');
                loadCounselors();
            } else {
                alert('删除失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            console.error('删除辅导员失败:', error);
            alert('删除辅导员失败: ' + error.message);
        }
    }

    function searchCounselors() {
        const keyword = document.getElementById('counselorSearchInput').value.toLowerCase();
        if (!keyword) {
            loadCounselors();
            return;
        }

        const filtered = counselors.filter(counselor =>
            (counselor.name && counselor.name.toLowerCase().includes(keyword)) ||
            (counselor.account && counselor.account.toLowerCase().includes(keyword))
        );
        renderCounselors(filtered);
    }

    function showAddCounselorModal() {
        const modal = document.getElementById('addCounselorModal');
        const categorySelect = document.getElementById('counselorCategory');
        categorySelect.innerHTML = '';

        if (categories.length === 0) {
            categorySelect.innerHTML = '<option value="">暂无可用类别</option>';
            alert('请先创建专业类别再添加辅导员');
            modal.style.display = 'block';
            return;
        }

        categories.forEach(category => {
            const option = document.createElement('option');
            option.value = String(category.id);
            option.textContent = category.name;
            categorySelect.appendChild(option);
        });

        modal.style.display = 'block';
    }

    function closeAddCounselorModal() {
        document.getElementById('addCounselorModal').style.display = 'none';
    }

    // ==================== 工具函数 ====================
    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    function formatDate(dateString) {
        if (!dateString) return '-';
        try {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        } catch (e) {
            return dateString;
        }
    }

    function debugCategories() {
        console.log('=== 类别调试信息 ===');
        console.log('当前学院ID:', currentCollegeId);
        console.log('类别列表:', categories);
        categories.forEach((cat, index) => {
            console.log(`类别${index + 1}:`, {
                id: cat.id,
                id类型: typeof cat.id,
                name: cat.name,
                collegeId: cat.collegeId
            });
        });
    }

    // 点击模态框外部关闭
    window.onclick = function (event) {
        const modals = [
            'addIndicatorPointModal',
            'editIndicatorPointModal',
            'addCategoryModal',
            'editCategoryModal',
            'addCounselorModal'
        ];

        modals.forEach(modalId => {
            const modal = document.getElementById(modalId);
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        });
    }
</script>
</body>
</html>

